﻿using CommunityToolkit.Mvvm.Input;
using ICSharpCode.AvalonEdit;
using Notifications.Wpf;
using System.IO;
using System.Text;
using System.Windows.Input;
using VideoTools.Extension;
using VideoTools.Util;
using VideoTools.vo;
using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;

namespace VideoTools.Commands
{
    public class SubtitleTimelineCommands : NotifyPropertyBase
    {
        private static volatile SubtitleTimelineCommands _instance;
        private static readonly object SyncRoot = new object();
        private static readonly string autoSaveEndWith = "__timeline_out";
        private static readonly string autoSaveTradEndWith = "__繁体__timeline_out";
        private static readonly string autoSaveSimpEndWith = "__简体__timeline_out";
        private static readonly string autoSaveTextEndWith = "__notimeline_out.txt";
        public static SubtitleTimelineCommands Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new SubtitleTimelineCommands();
                        }
                    }
                }

                return _instance;
            }
        }

        private SubtitleTimelineCommands() { }

        private bool _CheckSubtitleFileEnable;
        public bool CheckSubtitleFileEnable
        {
            get => _CheckSubtitleFileEnable;
            set => SetProperty(ref _CheckSubtitleFileEnable, value);
        }
        private bool _SetSubtitleTimelineEnable;
        public bool SetSubtitleTimelineEnable
        {
            get => _SetSubtitleTimelineEnable;
            set => SetProperty(ref _SetSubtitleTimelineEnable, value);
        }
        private bool _SetSubtitleTraditionEnable;
        public bool SetSubtitleTraditionEnable
        {
            get => _SetSubtitleTraditionEnable;
            set => SetProperty(ref _SetSubtitleTraditionEnable, value);
        }

        private bool _SetSubtitleSimpleEnable;
        public bool SetSubtitleSimpleEnable
        {
            get => _SetSubtitleSimpleEnable;
            set => SetProperty(ref _SetSubtitleSimpleEnable, value);
        }

        private bool _ExportSubtitleEnable;
        public bool ExportSubtitleEnable
        {
            get => _ExportSubtitleEnable;
            set => SetProperty(ref _ExportSubtitleEnable, value);
        }

        
        private string _Subtitle;

        public string Subtitle
        {
            get => _Subtitle;
            set => SetProperty(ref _Subtitle, value);
        }

        private string _SubtitleFile;

        public string SubtitleFile
        {
            get => _SubtitleFile;
            set => SetProperty(ref _SubtitleFile, value);
        }

        private string srtFileExt = "";
        private ICommand _CheckSubtitleFileCommand;
        private ICommand _OpenSubtitleFileCommand;
        private ICommand _SetSubtitleTimelineCommand;
        private ICommand _SetSubtitleTraditionCommand;
        private ICommand _SetSubtitleSimpleCommand;
        private ICommand _ExportSubtitleCommand;

        public ICommand CheckSubtitleFileCommand =>
            _CheckSubtitleFileCommand
            ?? (
                _CheckSubtitleFileCommand = new RelayCommand<object>(o =>
                {
                    TextEditor te = o as TextEditor;
                    bool check = SubtitleUtils.checkSub(te);
                    if (!check)
                    {
                        return;
                    }
                    SetSubtitleTraditionEnable = true;
                    SetSubtitleSimpleEnable = true;
                    ExportSubtitleEnable = true;
                    SetSubtitleTimelineEnable = true;
                    te.Save(SubtitleFile);
                })
            );

        public ICommand OpenSubtitleFileCommand =>
            _OpenSubtitleFileCommand
            ?? (
                _OpenSubtitleFileCommand = new RelayCommand<object>(o =>
                {
                    TextEditor te = o as TextEditor;
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "字幕文件(*.srt)|*.srt";
                    openFileDialog.RestoreDirectory = true;
                    openFileDialog.FilterIndex = 1;
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        SetSubtitleTraditionEnable = false;
                        SetSubtitleSimpleEnable = false;
                        ExportSubtitleEnable = false;
                        SetSubtitleTimelineEnable = false;
                        CheckSubtitleFileEnable = true;
                        SubtitleFile = openFileDialog.FileName;
                        srtFileExt = System.IO.Path.GetExtension(SubtitleFile);
                        var cnt = Utils.ReadFile(SubtitleFile);
                        te.Text = cnt.content;
                        checkOld(te);
                    }
                    else
                    {
                        return;
                    }
                })
            );

        
        private void checkOld(TextEditor te)
        {
            if (te == null)
            {
                return;
            }
            List<string> lines = te.GetLines();
            var check = SubtitleUtils.checkSubtitle(lines);
            SubTitleError error = check.error;
            //Console.WriteLine("res " + error.ToString());
            int lineNumber = check.line;
            if (error != SubTitleError.OK)
            {
                var content = new NotificationContent()
                {
                    Title = "似乎字幕文件格式有点问题",
                    Type = NotificationType.Error,
                    Message = "原因\n" + error.Desc() + "\n行数:" + lineNumber,
                };
                AppManager.Instance.NotificationManager.Show(content);
                if (lineNumber > 0 && lineNumber <= lines.Count)
                {
                    te.GotoLineAndHightLight(lineNumber);
                }
                SetSubtitleTraditionEnable = false;
                SetSubtitleSimpleEnable = false;
                //ExportSubtitleEnable = false;
                //SetSubtitleTimelineEnable = false;
                return;
            }
            else
            {
                SetSubtitleTraditionEnable = true;
                SetSubtitleSimpleEnable = true;
                ExportSubtitleEnable = true;
                SetSubtitleTimelineEnable = true;

                string savaPath = SubtitleFile.Replace(srtFileExt, autoSaveEndWith + srtFileExt);
                te.Save(savaPath);
            }
        }
        
        
        public ICommand SetSubtitleTimelineCommand =>
            _SetSubtitleTimelineCommand
            ?? (_SetSubtitleTimelineCommand = new RelayCommand<object>(o => {
                TextEditor te = o as TextEditor;
                if (te == null)
                {
                    return;
                }
                List<string> lines = te.GetLines();
                var res = SubtitleUtils.ReadSubtitle(lines);
                List<Subtitle> subtitles = res.list;
                // 调整字幕时间轴
                subtitles = SubtitleUtils.AdjustSubtitleTiming(subtitles);

                //oldTxts.Clear();
                List<string> subs = new List<string>();
                StringBuilder sb = new StringBuilder();
                // 输出调整后的字幕
                for (int i = 0; i < subtitles.Count; i++)
                {
                    sb.AppendLine(subtitles[i].ToString());
                    if (i != subtitles.Count - 1)
                    {
                        //sb.Append("\n");
                    }
                    subs.Add(subtitles[i].ToString());
                }
                string savaPath = SubtitleFile.Replace(srtFileExt, autoSaveEndWith + srtFileExt);
                //Console.WriteLine(savaPath);
                File.WriteAllLines(savaPath, subs);
            }));
        public ICommand SetSubtitleTraditionCommand =>
            _SetSubtitleTraditionCommand
            ?? (_SetSubtitleTraditionCommand = new RelayCommand<object>(o => {
                TextEditor te = o as TextEditor;
                SetSubtitleTimelineCommand.ExecuteIfCan(o);
                string saveText = ChineseConverter.Convert(te.Text, ChineseConversionDirection.SimplifiedToTraditional);
                string savaPath = SubtitleFile.Replace(srtFileExt, autoSaveTradEndWith + srtFileExt);
                Subtitle = saveText;
                te.Text = Subtitle;
                Console.WriteLine(savaPath);
                File.WriteAllText(savaPath, saveText);
            }));
        public ICommand SetSubtitleSimpleCommand =>
            _SetSubtitleSimpleCommand
            ?? (_SetSubtitleSimpleCommand = new RelayCommand<object>(o => {
                TextEditor te = o as TextEditor;
                SetSubtitleTimelineCommand.ExecuteIfCan(o);
                string saveText = ChineseConverter.Convert(te.Text, ChineseConversionDirection.TraditionalToSimplified);
                string savaPath = SubtitleFile.Replace(srtFileExt, autoSaveSimpEndWith + srtFileExt);
                Console.WriteLine(savaPath);
                Subtitle = saveText;
                te.Text = Subtitle;
                File.WriteAllText(savaPath, saveText);
            }));

       

        public ICommand ExportSubtitleCommand =>
            _ExportSubtitleCommand
            ?? (_ExportSubtitleCommand = new RelayCommand<object>(o => {
                TextEditor te = o as TextEditor;

                List<string> textList = SubtitleUtils.exportSubTitleText(te.GetLines());
                if (textList != null && textList.Count > 0)
                {
                    string savaPath = SubtitleFile.Replace(srtFileExt, autoSaveTextEndWith);
                    Console.WriteLine(savaPath);
                    File.WriteAllLines(savaPath, textList);
                }
            }));


    }
}
